package com.ghsc.ghxc.jsb.ui.my.activity

import android.graphics.Color
import android.text.TextUtils
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.gone
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.ext.visible
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.api.getUserIdRidUrl
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.ActivityRealNameAuthBinding
import com.ghsc.ghxc.jsb.ui.bean.AddressBeanData
import com.ghsc.ghxc.jsb.ui.home.activity.WebViewActivity
import com.ghsc.ghxc.jsb.ui.my.bean.AddressJsonBean
import com.ghsc.ghxc.jsb.ui.my.bean.BackCartDataBean
import com.ghsc.ghxc.jsb.ui.my.view.PayCardListViewPopup
import com.ghsc.ghxc.jsb.utils.JsonUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.my.activity
 * 类名：RealNameAuthActivity
 * 创建时间：2024/4/24 20:04
 * 创建人 @author： xiaolin
 * 描述 ：Todo...实名认证
 */
class RealNameAuthActivity : BaseVMActivity<RealNameAuthViewModel, ActivityRealNameAuthBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_real_name_auth
    }

    override fun attachVMClass(): Class<RealNameAuthViewModel>? {
        return  RealNameAuthViewModel::class.java
    }


    var ifold :Int=0



    private var backCartDataBean :BackCartDataBean?=null


    private var options1Items: List<AddressJsonBean> = ArrayList()
    private val options2Items = ArrayList<ArrayList<String>>()
    private val options3Items = ArrayList<ArrayList<ArrayList<String>>>()
    private var province = ""
    private var city = ""
    private var area = ""

    private var address=""

    override fun initView() {
        binding.bar.topTitle.text="实名认证"
        binding.bar.topLeftView.setOnClickListener { finish() }
        mViewModel.onUserInfoMethod()
    }
    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initClickListener() {
        super.initClickListener()
        binding.btnClose.setSingleClickListener { finish() }
        binding.btnLogin.setSingleClickListener {
            //提交审核
            if(backCartDataBean==null){
                showToast("请选择银行卡")
                mViewModel.onBankCardListMethod()
                return@setSingleClickListener
            }
            if(ifold==1){
                val map = HashMap<String,Any>()
                map["cid"] = backCartDataBean!!.cid
                map["province"] = ""
                map["city"] = ""
                map["area"] = ""
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onRenZhengMethod(it1) }
            }else{
                if(!TextUtils.isEmpty(province) && !TextUtils.isEmpty(city) && !TextUtils.isEmpty(area)) {
                    val map = HashMap<String,Any>()
                    map["cid"] = backCartDataBean!!.cid
                    map["province"] = province
                    map["city"] = city
                    map["area"] =area
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onRenZhengMethod(it1) }
                }else{
                    showToast("请选择归属地")
                    //弹出选择地址
                    initAddressData()
                    return@setSingleClickListener
                }
            }
        }

        binding.tvBankCard.setSingleClickListener{
            //选择银行卡
            mViewModel.onBankCardListMethod()
        }
        binding.btnIfOldStr.setSingleClickListener {
            //选择归属地
            initAddressData()
        }
    }

    private fun initAddressData(){
        val jsonData: String = JsonUtils.getJson(this, "areaData.json")
        val addressBean = GsonUtil.gsonToJsonClass(jsonData, AddressBeanData::class.java)
        options1Items = addressBean
        for (i in addressBean.indices) { //遍历省份
            val cityList = ArrayList<String>() //该省的城市列表（第二级）
            val province_AreaList = ArrayList<ArrayList<String>>() //该省的所有地区列表（第三极）
            for ( c in addressBean[i].children.indices) { //遍历该省份的所有城市
                val cityName = addressBean[i].children[c].name
                cityList.add(cityName) //添加城市
                val city_AreaList = ArrayList<String>() //该城市的所有地区列表
                for (a in addressBean[i].children[c].children.indices) {
                    city_AreaList.add(addressBean[i].children[c].children[a].name)
                }
                province_AreaList.add(city_AreaList) //添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(cityList)
            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList)
        }
        showPickerView()
    }
    /**
     * 弹出选择器
     */
    private fun showPickerView() {
        var provinceIndex = 0
        var cityIndex = 0
        var areaIndex = 0
        options1Items.forEachIndexed { index1, options1Item ->
            if (options1Item.name == province) {
                provinceIndex = index1
                options2Items[index1].forEachIndexed { index2, option2Item ->
                    if (option2Item == city) {
                        cityIndex = index2
                        options3Items[index1][index2].forEachIndexed { index3, options3Item ->
                            if (options3Item == area) {
                                areaIndex = index3
                            }
                        }
                    }
                }
            }
        }
        val pvOptions: OptionsPickerView<Any> = OptionsPickerBuilder(
            this
        ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
            val opt1tx =
                if (options1Items.isNotEmpty()) options1Items[options1].pickerViewText else ""
            val opt2tx =
                if (options2Items.size > 0 && options2Items[options1].size > 0) options2Items[options1][options2] else ""
            val opt3tx =
                if (options2Items.size > 0 && options3Items[options1].size > 0 && options3Items[options1][options2].size > 0) options3Items[options1][options2][options3] else ""
            province = opt1tx
            city = opt2tx
            area = opt3tx
            address = "$province · $city · $area";
            binding.ifOldStr.visible()
            binding.ifOldStr.text=address
        }
            .setTitleText("地址选择")
            .setDividerColor(Color.BLACK)
            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
            .setSelectOptions(provinceIndex, cityIndex, areaIndex)
            .setItemVisibleCount(10)
            .setLineSpacingMultiplier(2.2f)
            .setContentTextSize(16)
            .setTitleSize(16)
            .setSubCalSize(16)
            .setCancelColor(0xFF666666.toInt())
            .setSubmitColor(0xFFEC2D69.toInt())
            .build()
        pvOptions.setPicker(
            options1Items, options2Items as List<MutableList<Any>>?,
            options3Items as List<MutableList<MutableList<Any>>>?
        ) //三级选择器
        pvOptions.show()
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@RealNameAuthActivity) {
                dismissLoading()
                showToast(it)
            }
            againLoginMsg.observe(this@RealNameAuthActivity) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }

            onUserInfoData.observe(this@RealNameAuthActivity) {
                var userInfo =it.data.data
                if(userInfo.ifrenzheng==1){
                    //认证过
                    binding.llNo.gone()
                    binding.llYes.visible()
                    binding.xingming.text=userInfo.xingming
                    binding.gsd.text=userInfo.province+" · "+userInfo.city+" · "+userInfo.area
                }else{
                    //未认证
                    binding.llYes.gone()
                    binding.llNo.visible()
                    binding.llBankCardBean.gone()
                    binding.llIfold.gone()
                    binding.ifOldStr.gone()
                }
            }

            onBankCardListData.observe(this@RealNameAuthActivity){
                //选择银行卡
                if(it.data.list.size>0){
                    XPopup.Builder(this@RealNameAuthActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                    .customHostLifecycle(lifecycle)
                    .dismissOnTouchOutside(true)
                    .hasShadowBg(true)
                    .asCustom(PayCardListViewPopup(this@RealNameAuthActivity,it.data.list, object :
                        PayCardListViewPopup.ConfirmClickListener{
                        override fun onConfirm(cheBean: BackCartDataBean) {
                            backCartDataBean =cheBean
                            binding.cardName.text=cheBean.card_name+" "+cheBean.bank_name
                            binding.cardType.text=cheBean.card_type+" "+cheBean.card_id
                            binding.llBankCardBean.visible()
                            //根据身份证获取归属地
                            val map: HashMap<String, Any> = HashMap()
                            map["sfzno"] = cheBean.sfzno
                            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSfzAreaMethod(it1) }
                        }

                    }))
                    .show()
                }else{
                    val config = UserManager.getConfig()
                    config?.let {
                        var sysConfigResultData = it.getSysConfigBean(CustKey.configK3)
                        if(sysConfigResultData!=null)
                            if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
                                startKtxActivity<WebViewActivity>(
                                    values = arrayListOf(
                                        "url" to sysConfigResultData.cfg_value+ getUserIdRidUrl(),
                                        "showBar" to false,
                                        "title" to sysConfigResultData.cfg_memo,
                                    )
                                )
                            }
                    }
                }
            }
            onSfzAreaData.observe(this@RealNameAuthActivity){
                //根据身份证获取归属地
                ifold =it.data.data2.ifold
                if(it.data.data.size==3){
                    province=it.data.data[0]
                    city=it.data.data[1]
                    area=it.data.data[2]
                    address = "$province · $city · $area";
                }
                if (ifold!=1) {
                    binding.llIfold.visible()
                    if(!TextUtils.isEmpty(address)){
                        binding.ifOldStr.visible()
                        binding.ifOldStr.text=address
                    }
                }else{
                    binding.llIfold.gone()
                    binding.ifOldStr.gone()
                }
            }
            onRenZhengData.observe(this@RealNameAuthActivity){
                showToast("认证成功")
                mViewModel.onUserInfoMethod()
            }
        }
    }

}